<template>
  <a-modal
    :title="title"
    :width="1000"
    :visible="visible"
    @cancel="handleCancel"
    :footer="null">
    
    <a-spin :spinning="confirmLoading">
      <div ref="printArea" class="print-area">
        <div class="print-header">
          <h1>采购单</h1>
          <div class="print-no">单号：{{ purchaseOrder.purchaseNo }}</div>
        </div>
        
        <div class="print-info">
          <div class="info-row">
            <div class="info-col">
              <div class="info-item">
                <span class="label">预计到货日期：</span>
                <span class="value">{{ purchaseOrder.expectedArrivalDate }}</span>
              </div>
              <div class="info-item">
                <span class="label">状态：</span>
                <span class="value">
                  <j-dict-tag :value="purchaseOrder.status || ''" dictCode="purchase_order_status"/>
                </span>
              </div>
            </div>
            <div class="info-col">
              <div class="info-item">
                <span class="label">审核人：</span>
                <span class="value">{{ purchaseOrder.approveBy || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="label">审核时间：</span>
                <span class="value">{{ purchaseOrder.approveTime || '-' }}</span>
              </div>
            </div>
            <div class="info-col">
              <div class="info-item">
                <span class="label">总金额：</span>
                <span class="value highlight">¥{{ purchaseOrder.totalAmount ? parseFloat(purchaseOrder.totalAmount).toFixed(2) : '0.00' }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 按物料类型分组显示 -->
        <div v-for="(group, type) in groupedMaterials" :key="type" class="material-group">
          <h3 class="group-title">{{ getMaterialTypeName(type) }}</h3>
          
          <div class="print-table">
            <table>
              <thead>
                <tr>
                  <th>序号</th>
                  <th>物料编码</th>
                  <th>物料名称</th>
                  <th>规格型号</th>
                  <th>供应商</th>
                  <th>单位</th>
                  <th>数量</th>
                  <th>单价</th>
                  <th>金额</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in group.items" :key="item.id">
                  <td>{{ index + 1 }}</td>
                  <td>{{ item.materialCode }}</td>
                  <td>{{ item.materialName }}</td>
                  <td>{{ item.specification }}</td>
                  <td>{{ item.supplierName || '-' }}</td>
                  <td>{{ item.unit }}</td>
                  <td>{{ item.quantity }}</td>
                  <td>¥{{ item.unitPrice ? parseFloat(item.unitPrice).toFixed(2) : '0.00' }}</td>
                  <td>¥{{ item.amount ? parseFloat(item.amount).toFixed(2) : '0.00' }}</td>
                </tr>
                <!-- 小计行 -->
                <tr class="subtotal-row">
                  <td colspan="8" class="text-right">小计：</td>
                  <td>¥{{ group.totalAmount.toFixed(2) }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        
        <div class="print-footer">
          <div class="remark">
            <span class="label">备注：</span>
            <span class="value">{{ purchaseOrder.remark || '无' }}</span>
          </div>
          <div class="signature">
            <div class="sign-item">
              <span class="label">供应商签字：</span>
              <span class="value">_______________</span>
            </div>
            <div class="sign-item">
              <span class="label">采购员签字：</span>
              <span class="value">_______________</span>
            </div>
            <div class="sign-item">
              <span class="label">日期：</span>
              <span class="value">_______________</span>
            </div>
          </div>
        </div>
      </div>
      
      <div class="print-actions">
        <a-button @click="handleCancel">关闭</a-button>
        <a-button type="primary" icon="printer" @click="handlePrint" style="margin-left: 8px;">打印</a-button>
        <a-button icon="download" @click="exportPDF" style="margin-left: 8px;">导出PDF</a-button>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
import { getAction } from '@/api/manage'
import JDictTag from '@/components/dict/JDictTag'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'

export default {
  name: 'PurchasePrintModal',
  components: {
    JDictTag
  },
  data() {
    return {
      title: '打印采购单',
      visible: false,
      confirmLoading: false,
      purchaseOrder: {},
      detailList: [],
      url: {
        detail: '/wms/purchase/queryById',
        detailList: '/wms/purchase/detail/list'
      },
      materialTypeDictMap: {
        '1': '型材',
        '2': '配件',
        '3': '辅件',
        '4': '其他'
      }
    }
  },
  computed: {
    // 按物料类型分组
    groupedMaterials() {
      const groups = {};
      
      this.detailList.forEach(item => {
        const type = item.materialType || '0';
        
        if (!groups[type]) {
          groups[type] = {
            items: [],
            totalAmount: 0
          };
        }
        
        groups[type].items.push(item);
        groups[type].totalAmount += parseFloat(item.amount || 0);
      });
      
      return groups;
    }
  },
  methods: {
    show(id) {
      this.visible = true;
      this.loadData(id);
    },
    loadData(id) {
      this.confirmLoading = true;
      
      // 加载采购单基本信息
      getAction(this.url.detail, { id }).then(res => {
        if (res.success) {
          this.purchaseOrder = res.result || {};
          
          // 加载采购单明细
          this.loadDetailList(id);
        } else {
          this.$message.error(res.message || '加载采购单详情失败');
          this.confirmLoading = false;
        }
      }).catch(() => {
        this.confirmLoading = false;
      });
    },
    // 在detailList加载后处理单位信息
    loadDetailList(purchaseOrderId) {
      getAction(this.url.detailList, { purchaseOrderId }).then(res => {
        if (res.success) {
          this.detailList = res.result || [];
          
          // 确保每个明细项都有单位信息
          this.detailList.forEach(item => {
            // 如果供应商提供了单位信息，优先使用供应商的单位
            if (!item.unit && item.supplierUnit) {
              item.unit = item.supplierUnit;
            }
          });
        } else {
          this.$message.error(res.message || '加载采购单明细失败');
        }
        this.confirmLoading = false;
      }).catch(() => {
        this.confirmLoading = false;
      });
    },
    getMaterialTypeName(type) {
      return this.materialTypeDictMap[type] || '未分类';
    },
    handleCancel() {
      this.visible = false;
      this.purchaseOrder = {};
      this.detailList = [];
    },
    handlePrint() {
      // 使用浏览器打印功能
      const printContent = this.$refs.printArea.innerHTML;
      const printWindow = window.open('', '_blank', 'height=600,width=800');
      
      printWindow.document.write(`
        <html>
          <head>
            <title>采购单打印</title>
            <style>
              body { font-family: Arial, sans-serif; margin: 20px; }
              .print-header { text-align: center; margin-bottom: 20px; }
              .print-header h1 { margin-bottom: 5px; }
              .print-no { font-size: 14px; }
              .print-info { margin-bottom: 20px; }
              .info-row { display: flex; flex-wrap: wrap; }
              .info-col { flex: 1; min-width: 200px; }
              .info-item { margin-bottom: 5px; }
              .label { font-weight: bold; }
              .highlight { color: #f5222d; font-weight: bold; }
              .material-group { margin-bottom: 20px; }
              .group-title { background-color: #f5f5f5; padding: 8px; margin-bottom: 10px; }
              .print-table table { width: 100%; border-collapse: collapse; margin-bottom: 15px; }
              .print-table th, .print-table td { border: 1px solid #000; padding: 8px; text-align: center; font-size: 12px; }
              .print-table th { background-color: #f2f2f2; }
              .subtotal-row { background-color: #f9f9f9; }
              .text-right { text-align: right; }
              .total-table { margin-top: 20px; }
              .print-footer { margin-top: 30px; }
              .remark { margin-bottom: 20px; }
              .signature { display: flex; justify-content: space-between; margin-top: 50px; }
              .sign-item { flex: 1; }
            </style>
          </head>
          <body>
            ${printContent}
          </body>
        </html>
      `);
      
      printWindow.document.close();
      printWindow.focus();
      
      // 延迟打印，确保内容加载完成
      setTimeout(() => {
        printWindow.print();
        printWindow.close();
      }, 500);
    },
    // 导出为PDF
    exportPDF() {
      const element = this.$refs.printArea;
      const opt = {
        margin: 10,
        filename: `采购单_${this.purchaseOrder.purchaseNo}.pdf`,
        image: { type: 'jpeg', quality: 0.98 },
        html2canvas: { scale: 2 },
        jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
      };
      
      html2canvas(element).then(canvas => {
        const imgData = canvas.toDataURL('image/jpeg');
        const pdf = new jsPDF(opt.jsPDF.orientation, opt.jsPDF.unit, opt.jsPDF.format);
        const imgProps = pdf.getImageProperties(imgData);
        const pdfWidth = pdf.internal.pageSize.getWidth();
        const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
        
        pdf.addImage(imgData, 'JPEG', 0, 0, pdfWidth, pdfHeight);
        pdf.save(opt.filename);
      });
    }
  }
}
</script>

<style scoped>
.print-area {
  padding: 20px;
  background-color: #fff;
}

.print-header {
  text-align: center;
  margin-bottom: 20px;
}

.print-header h1 {
  margin-bottom: 5px;
}

.print-no {
  font-size: 14px;
}

.print-info {
  margin-bottom: 20px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 16px;
  background-color: #fafafa;
}

.info-row {
  display: flex;
  flex-wrap: wrap;
}

.info-col {
  flex: 1;
  min-width: 200px;
}

.info-item {
  margin-bottom: 5px;
}

.label {
  font-weight: bold;
  margin-right: 5px;
}

.highlight {
  color: #f5222d;
  font-weight: bold;
}

.material-group {
  margin-bottom: 20px;
}

.group-title {
  background-color: #f5f5f5;
  padding: 8px 16px;
  margin-bottom: 10px;
  border-left: 4px solid #1890ff;
  border-radius: 2px;
}

.print-table table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 15px;
}

.print-table th,
.print-table td {
  border: 1px solid #000;
  padding: 8px;
  text-align: center;
}

.print-table th {
  background-color: #f2f2f2;
}

.subtotal-row {
  background-color: #f9f9f9;
  font-weight: bold;
}

.text-right {
  text-align: right;
}

.total-table {
  margin-top: 20px;
}

.print-footer {
  margin-top: 30px;
}

.remark {
  margin-bottom: 20px;
}

.signature {
  display: flex;
  justify-content: space-between;
  margin-top: 50px;
}

.sign-item {
  flex: 1;
}

.print-actions {
  margin-top: 20px;
  text-align: center;
}
</style> 